{% extends "school/layout.html" %}

{% set page_title = translate('学生账号管理') %}

{% block content %}
<style>
    .checkA{
        text-decoration: underline;
        color: red!important;
    }
</style>
<div class="m-student-list">
    <div class="m-fixed-table-top">
        <div class="title">
            <div class="name">
                {% if music_class %}
                {{ music_class.name }}
                <a class="modified" href="{{ url_for('school.edit_class', cid=music_class.id) }}">{{translate('修改')}}</a>
                {% elif music_class == {} %}
                {{translate('未分配班级学生')}}
                {% else %}
                {{translate('全部学生')}}
                {% endif %}
            </div>
            <p class="text">
            <span>{{translate('学生')}}：{{ pagination.total }} {{translate('人')}}</span>
            {% if music_class %}<span>{{translate('任课教师')}}：{{ music_class.teacher.name }}</span>{% endif %}
            {% if music_class %}<span>{{translate('教室')}}：{{ music_class.classroom.name }}</span>{% endif %}
            </p>
        </div>
        <div class="toolbars">
            {% if not in_user_verify_whitelist %}
            <label class="lessonType">{{translate('课程类型')}}： </label>
            <select class="sselect lessonType" id="courseTypeSelect">
                <option value="" {% if course_type == '' %} selected {% endif %} >{{translate('全部')}}</option>
                <option value="course_children" {% if course_type == 'course_children' %} selected {% endif %} >{{translate('儿童课程')}}</option>
                <option value="course_adults" {% if course_type == 'course_adults' %} selected {% endif %} >{{translate('流行经典')}}</option>
                <option value="course_xi_yang_hong" {% if course_type == 'course_xi_yang_hong' %} selected {% endif %} >{{translate('怀旧金曲')}}</option>
            {% endif %}
            </select>
            <label>{{translate('班级类型')}}： </label>
            <select class="sselect" id="typeselect">
                <option value="all" {% if music_class_stat == 'all' %} selected {% endif %} >{{translate('全部')}}</option>
                <option value="normal_class" {% if music_class_stat == 'normal_class' %} selected {% endif %} >{{translate('正式班')}}</option>
                <option value="exp_class" {% if music_class_stat == 'exp_class' %} selected {% endif %} >{{translate('体验班')}}</option>
            </select>
            <label>{{translate('状态')}}： </label>
            <select class="sselect" id="studentselect">
                <option value="all" {% if stat == 'all' %} selected {% endif %} >{{translate('全部')}}</option>
                <option value="onboard" {% if stat == 'onboard' %} selected {% endif %} >{{translate('在读')}}</option>
                <option value="deleted" {% if stat == 'deleted' %} selected {% endif %} >{{translate('删除')}}</option>
            </select>
            <span class="new" id="createnew">{{translate('新建')}}</span>
            <span class="del disabled">{{translate('删除')}}</span>
            <form action="/school/students/search" method="POST">
                <input type="text" name="keyword" placeholder="姓名、用户名、手机号">
                <input type="submit" value="搜索" class="new">
            </form>
            {# 批量移动功能暂时去掉，问题号COS-856
            <div class="move disabled">
                <span>{{translate('移动至')}}</span>
                <select id="move_student_ids">
                    {%- for c in classes %}
                    <option value="{{ c.id }}">{{ c.name }}</option>
                    {% endfor -%}
                </select>
                <input type="hidden" id="move_students"/>
            </div>
            #}
            <a class="export" id="export">{{translate('导出Excel列表')}}</a>
        </div>
    </div>
    <table class="table table-condensed table-striped table-bordered m-ul-table" data-toggle="table">
        <thead>
            <tr>
                <th><input type="checkbox" {% if stat == "deleted" %}disabled{% endif %}></th>
                <th data-sortable="true" data-sorter="sortContent">{{translate('学生姓名')}}</th>
                <th data-sortable="true" data-sorter="sortContent">{{translate('用户名')}}</th>
                <th data-sortable="true" class="col_sex">{{translate('性别')}}</th>
                <th data-sortable="true" class="col_age">{{translate('年龄')}}</th>
                <th data-sortable="true">{{translate('联系电话')}}</th>
                <th data-sortable="true">{{translate('所在班级')}}</th>
                <th data-sortable="true">{{translate('班级类型')}}</th>
                {% if not in_user_verify_whitelist %}
                <th data-sortable="true">{{translate('课程类型')}}</th>
                <th data-sortable="true" class="col_ver">{{translate('身份验证')}}</th>
                {% endif %}
                <th data-sortable="true" data-sorter="sortContent">{{translate('最新成绩')}}</th>
                <th data-sortable="true" data-sorter="sortContent">{{translate('状态')}}</th>
                {# comment out
                <th>{{translate('出勤率')}}</th>
                <th>{{translate('上一次上课时间')}}</th>
                #}
                <th>{{translate('管理')}}</th>
            </tr>
        </thead>
        <tbody>
            {% for st in students %}
            <tr id="{{ st.id }}">
                <td><input type="checkbox" name="student_ids" value="{{ st.id }}" {% if st.active == False %}disabled{% endif %}></td>
                <td><a href="{{ url_for('school.edit_student', sid=st.id) }}">{{ st.name }}</a></td>
                <td><a href="{{ url_for('school.edit_student', sid=st.id) }}">{{ st.username }}</a></td>
                <td class="col_sex">{{ translate(st.gender) }}</td>
                <td class="col_age">{{ st.age }}</td>
                <td>{{ st.parent_phone }}</td>
                {% if st.class_id %}
                <td><a href="{{ url_for('school.list_classstudents', cid=st.class_id) }}">{{ st.class_name }}</a></td>
                {% else %}
                <td><a href="{{ url_for('school.list_classstudents', cid=0) }}">{{translate('未分配')}}</a></td>
                {% endif %}
                {% if st.active %}
                    <td>{{ translate(st.class_type) }}</td>
                {% else %}
                    <td>-</td>
                {% endif %}
                {% if not in_user_verify_whitelist %}
                <td class="courseType">{{ st.course_type }}</td>
                {% if st.active %}
                    {% if st.is_verified %}<td>{{translate('已验证')}}</td>{% else %}<td><a href="" class="checkA">{{translate('未验证')}}</a></td>{%endif %}
                {% else %}
                    <td>-</td>
                {% endif %}
                {% endif %}
                <td>
                    <a href="{{ url_for('school.show_study_sessions', student_id=st.id) }}">{{ translate('查看成绩') }}</a>
                </td>
                {# comment out
                <td>{{ st.attendance }}</td>
                <td>2015/03/26</td>
                #}
                {% if st.active == True %}
                    <td>{{translate('在读')}}</td>
                {% else %}
                    <td><font color="red">{{translate('删除')}}</font></td>
                {% endif %}
                {% if st.active == True %}
                    <td>
                        <a href="{{ url_for('school.edit_student', sid=st.id) }}"><span class="glyphicon glyphicon-edit"></span></a><!--edit student-->
                        <a href="#"><span class="glyphicon glyphicon-trash"></span></a><!--delete student-->
                    </td>
                {% else %}
                    <td><font color="blue"><a href="" class="restorestudent">{{translate('还原')}}<a></font></td>
                {% endif %}
            </tr>
            {% endfor %}
        </tbody>
    </table>
    {% if not nopage %}
        {% include "school/pagination.html" %}
    {% endif %}
</div>
<div class="modal modal-confirm">
    <div class="modal-dialog modal-sm">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title">{{translate('确认删除')}}</h4>
            </div>
            <div class="modal-body">
                <button class="btn btn-danger">{{translate('确认')}}</button>
                <button class="btn btn-default btn-close">{{translate('取消')}}</button>
            </div>
        </div>
    </div>
</div>
<div class="modal" id="checkModal">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
                <h4 class="modal-title">{{translate('验证手机号码')}}</h4>
            </div>
            <div class="modal-body">
                <form class="form-horizontal">
                    <div class="form-group">
                        <label class="control-label col-sm-2">{{translate('手机号码')}}</label>
                        <div class="col-sm-6">
                            <input type="tel" value="" id="phone" placeholder="{{translate('请输入手机号')}}" class="form-control">
                        </div>
                        <div class="col-sm-3">
                            <button class="btn btn-default" id="sendVerify">{{translate('发送验证码')}}</button>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="control-label col-sm-2">{{translate('验证码')}}</label>
                        <div class="col-sm-6">
                            <input type="tel" id="verify" value="" class="form-control" placeholder="{{translate('请输入6位验证码')}}">
                        </div>
                    </div>
                    <p class="tips"></p>
                    <div class="form-group" style="text-align: center;">
                        <button class="btn btn-default" id="done" style="width: 80px;margin-right: 30px;">{{translate('确定')}}</button>
                        <button class="btn btn-default" style="width: 80px" data-dismiss="modal">{{translate('取消')}}</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block js %}
<script type="text/javascript">
function sortContent(val1,val2){
    val1=val1.replace(/<a[^>]*?>/gi,"").replace('</a>','');
    val2=val2.replace(/<a[^>]*?>/gi,"").replace('</a>','');
    if(val1>val2)
        return 1;
    else
        return -1;
}
var url_mapping = {
    {% for stat in ["all", "onboard", "deleted"] %}
    {% for mc_stat in ["all", "normal_class", "exp_class"] %}
    {% for course_type in ["", "course_children", "course_adults", "course_xi_yang_hong"] %}
    "{{stat}},{{mc_stat}},{{course_type}}" : "{{ url_for ('school.list_students', stat=stat, mc_stat=mc_stat, course_type=course_type) | safe}}",
    {% endfor %}
    {% endfor %}
    {% endfor %}
}
$(function(){
    var countDown = 60;
    var isCounting = false;
    var t;
    var isSent = false;
    var stu_id = '';
    var stu_course_type = '';

    function change_url_by_stat() {
        var stat = document.getElementById("studentselect").value;
        var mc_stat = document.getElementById("typeselect").value;
        var course_type = document.getElementById("courseTypeSelect")?document.getElementById("courseTypeSelect").value:'';
        var title = stat+','+mc_stat+','+course_type;

        for(var i in url_mapping){
            if(title === i){
                window.location.href = url_mapping[i];
                break;
            }
        }
    }

    $('#downloadTemplate').click(function(){
        var url = '/static/' + (localStorage.lang=='lang=en'?'Student_Import_Template_en.xls' :'Student_Import_Template.xls');
        window.location.href = url;
    })
    $('#studentselect').bind('change', function() {
        change_url_by_stat();
    });
    $('#typeselect').bind('change', function() {
        change_url_by_stat();
    });
    $('#courseTypeSelect').bind('change', function() {
        change_url_by_stat();
    });

    $('.restorestudent').bind('click', function() {
        $.ajaxSetup({
            async : false
        });

        sid = $(this).parent().parent().parent().attr('id');
        var url = "/school/student/restore/" + sid
        if(localStorage.lang == 'lang=en'){
            url += '?'+localStorage.lang
        }
        $.post(url, function(data) {
            if (data['code'] != 0) {
                alert(data['msg'])
            }
            change_url_by_stat();
        }, 'json');
    });

    // click trash
    $('span.glyphicon-trash').bind('click',function(){
        sid = $(this).parent().parent().parent().attr('id');
        $('.modal-confirm').modal('show');

        // click modal alert confirm button
        $('.modal-confirm .btn-danger').bind('click',function(){
            var url = '/school/students/delete/' + window.sid;
            $.post(url, function(data){
                if (data['code']!=0){
                    alert(data['msg']);
                }
                change_url_by_stat();
                $('.modal-confirm').modal('hide');
            }, 'json');
        });
    });

    // click modal alert confirm/cancal button
    $('.modal-confirm .btn-close').bind('click',function(){
        $('.modal-confirm').modal('hide');
    });

    $('.upload-excel .info').bind('click',function(e){
        $('.modal-info').show();
        e.stopPropagation();
        e.preventDefault();
        return ;
    });
    $('.modal-info .btn,.modal-info .close').click(function(){
        $('.modal-info').hide();
    });
    // click new
    $('#createnew').bind('click',function(e){
        e.preventDefault();
        window.location.href = "{{ url_for('school.create_student') }}";
    });

    $('.upload-excel .upload').bind('click',function(){
        $('#file').click();
    });

    $('#file').on('change',function(){
        $('#upload-form').submit();
    });

    $('#file').bind('change', function(e){
        var fname = $(this).val();
        $('#fileform').submit();
    });

    $('#fileform').submit(function(event){
        var formData = new FormData($(this)[0]);

        $.ajax({
            url: $(this).attr("action"),
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function(data){
                change_url_by_stat();
            }
        });
    });

    // click move confirm
    $('#move_student_ids').change(function(){
        var ids = [];
        $('tbody :checked').each(function(){
            ids.push($(this).parent().parent().attr('id'));
        });
        if (!ids.length) {
            kalert('{{translate("请点击复选框选中要移动的学生")}}');
            return;
        }
        var data = {
            'ids': ids,
            'moveto': $(this).val()
        };
        var url = '{{ url_for('school.move_students') }}';
        if(localStorage.lang == 'lang=en'){
            url += '?'+localStorage.lang
        }
        $.post(url, data=data, function(data){
            if (data['code']!=0){
                alert(data['msg']);
                return;
            }
            else {
                window.location.reload(true)
            }
        }, 'json');
    });

    // click delete all
    $('.del').click(function(){
        var ids = [];
        $('tbody :checked').each(function(){
            ids.push($(this).parent().parent().attr('id'));
        });
        if (!ids.length) {
            alert('{{translate("请点击复选框选中要删除的学生")}}');
            return;
        }
        $('.modal-confirm').modal('show');

        var data = {
            'ids': ids
        };

        // click modal alert confirm button
        $('.modal-body button.btn-danger').bind('click',function(){
            var url = '/school/students/muti_delete';
            $.post(url, data=data, function(data){
                if (data['code']!=0){
                    alert(data['msg']);
                }
                change_url_by_stat();
                $('.modal-confirm').modal('hide');
            }, 'json');
        });

    });

    // click export data
    $('#export').click(function(){
        window.open('{{ url_for("school.export_data") }}{% if music_class %}?class_id={{ music_class.id }}{% endif %}'+(localStorage.lang=='lang=en'? '?'+ localStorage.lang:''));
    })
    function setTime(val){
      if(isCounting){
          val.attr('disabled','disabled');
          val.addClass('btn-disable');
           val.html('{{translate("在")}}'+countDown+'{{translate("秒后重新发送")}}');
          countDown--;
          if(countDown<0){
              isCounting = false;
              countDown = 60;
          }
      }else{
          val.removeAttr('disabled');
          val.removeClass('btn-disable');
          val.html('{{translate("发送验证码")}}');
          clearTimeout(t);
          return false;
      }
      t = setTimeout(function(){
          setTime(val);
      },1050);
    }

    function clearForm(){//清除表单
        $('#phone').val('');
        $('#verify').val('');
        $('#sendVerify').removeAttr('disabled');
        $('#sendVerify').removeClass('btn-disable');
        $('#sendVerify').html('{{translate("发送验证码")}}');
        clearTimeout(t);
        countDown = 60;
        stu_id = '';
        stu_course_type = '';
    }

    $('form button').click(function(e){//取消form表单的自动提交
        e.preventDefault();
    });

    $('.checkA').click(function(e){//打开弹出框
        e.preventDefault();
        clearForm();
        $('#checkModal').modal('show');
        stu_id = $(this).parent().parent()[0].id;
        var ct = $(this).parent().siblings('.courseType').text();
        if(ct == '{{translate("流行经典")}}'){
            stu_course_type = 'course_adults'
        }else if(ct == '{{translate("怀旧金曲")}}'){
            stu_course_type = 'course_xi_yang_hong'
        }else{
            stu_course_type = 'course_children'
        }
    });

    $('#sendVerify').click(function(){//发送验证码
        var $this = $(this);
        var phone = $.trim($('#phone').val());
        var pReg = new RegExp('^[0-9]{11}$')
        if(pReg.test(phone)){
            $.post('/school/students/check_phone',{'phone':phone,'course_type':stu_course_type},function(data){
                var d = JSON.parse(data);
                if(d.code == 0){
                    $.post('/vcode/send_vcode',{'phone':phone},function(data){
                        var da = JSON.parse(data);
                        if(da.meta.code == 0){
                            isCounting = true;
                            setTime($this);
                            isSent = true;
                        }else{
                            if(da.meta.code == 1){
                                kalert('{{translate("验证码不正确，请重新输入")}}');
                            }else if(da.meta.code == 2){
                                kalert('{{translate("发验证码失败，请稍后再试")}}');
                            }
                        }
                    });
                }else{
                    kalert('{{translate("输入的手机号已经被占用，请检查后重新输入！")}}')
                }
            });
        }else{
            if(phone == ''){
                kalert('{{translate("请输入手机号！")}}')
            }else{
                kalert('{{translate("输入的手机号不符合规范！")}}')
            }
        }

    });

    $('#done').click(function(){ //完成
        var phone = $.trim($('#phone').val());
        var ver = $.trim($('#verify').val());
        var vReg = new RegExp('^[0-9]{6}$');
        if(isSent){
            if(vReg.test(ver)){
                $.post('/school/students/verified',{
                    'sid': stu_id,
                    'phone': phone,
                    'vcode': ver
                },function(data){
                    var d = JSON.parse(data);
                    if(d.code == 0){
                        $('#checkModal').modal('hide');
                        kalert('{{translate("验证成功")}}');
                        setTimeout(function(){
                            window.location.reload();
                        },2000)
                    }else{
                        kalert('{{translate("验证码错误或已过期")}}')
                    }
                });
            }else{
                kalert('{{translate("请输入正确的6位短信验证码")}}')
            }

        }else{
            kalert('{{translate("请先输入手机获取短信验证码！")}}')
        }
    })
//验证手机号完成
});
</script>
{% endblock %}
